package org.jumiz.framework.base.reflect;

import org.jumiz.framework.base.support.BeanFactory;
import org.jumiz.framework.base.support.FieldAnnotationSupport;
import org.jumiz.framework.base.util.PropertyNameUtil;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.Function;

/**
 * 函数式接口
 * @author jumiz
 */
@FunctionalInterface
public interface SFunction<T, R> extends Function<T, R>, Serializable {

    default SFunctionDefinition<T> definition(SFunction<T, R> column)
            throws NoSuchMethodException, InvocationTargetException,
            IllegalAccessException, ClassNotFoundException {
        Method method = column.getClass().getDeclaredMethod("writeReplace");
        method.setAccessible(true);
        SerializedLambda lambda = (SerializedLambda)method.invoke(column);
        // 方法名称
        String methodName = lambda.getImplMethodName();
        // 字段名称
        String fieldName = PropertyNameUtil.methodToProperty(methodName);
        // 实体对象的class
        Class<T> aClass = (Class<T>) Class.forName(lambda.getImplClass().replaceAll("/", "."));
        // 调用扩展
        fieldName = BeanFactory.getBean(FieldAnnotationSupport.class).getFieldName(aClass, fieldName, methodName);
        return SFunctionDefinition.<T>builder().aClass(aClass).fieldName(fieldName).methodName(methodName).build();
    }
}
